package com.manage.test.web.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.manage.test.web.dto.MessageSendDto;
import com.manage.test.web.websocket.WebSocketServer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.redisson.codec.SerializationCodec;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

/**
 * @Author: zhangqing
 * @CreateTime: 2023-03-10 15:06
 * @Description: 在这里添加描述
 */
@Component
@Slf4j
@Data
public class RedisMessageListener implements MessageListener<String> {

    /**
     * 用户的session
     */
    private Session session;

    /**
     * 用户的ID
     */
    private String userId;

    @Override
    public void onMessage(CharSequence channel, String msg) {
        WebSocketServer webSocketServer = SpringUtil.getBean("webSocketServer");
        if (ObjectUtil.isNotNull(msg)) {
            synchronized (this) {
                if (channel.equals("test")) {
                    MessageSendDto messageSendDto = JSONUtil.toBean(msg.toString(), MessageSendDto.class);
                    //根据自身的业务需要编写
                    //下面是通过用户id，调用socket给对应的用户发送信息
                    if (messageSendDto.getType().equals("1")) {
                        if (StrUtil.equals(userId,String.valueOf(messageSendDto.getToUserId()))) {
                            System.out.println("redis订阅端,准备发送数据到websocket"+msg);
                            webSocketServer.sendMessageToUser(messageSendDto.getMessage(), String.valueOf(messageSendDto.getToUserId()));
                        }
                    }
                }
            }
        }
    }
}
